import PageContainer from '@/components/PageContainer';
import ProductConfig from '@/config/product';
import { useDeviceListStore, useDeviceShare, useHomeStore } from '@/hooks';
import useEvent from '@/hooks/useEvent';
import { isSameDevice } from '@/utils';
import { GStyleSheet } from '@/utils/DarkMode';
import { Button, Collapse } from '@taroify/core';
import { ScrollView, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import I18n from 'i18n-js';
import { observer } from 'mobx-react';
import { useEffect, useMemo, useState } from 'react';
import Device from './device';
import { toJS } from 'mobx';

const dstyles = GStyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'column',
    height: '100%',
  },
  rooms: {
    flex: 1,
    minHeight: 0,
  },
  item: {
    marginTop: '28rpx',
  },
  bottom: {
    height: 80,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  manageIcon: {
    width: 16,
    height: 16,
    marginRight: 10,
  },
  button: {
    width: 290,
  },
});

const AddShareDevices = () => {
  const homes = useHomeStore();
  const deviceShare = useDeviceShare();
  const devices = useDeviceListStore();
  const [selectedRoomId, setSelectedRoomId] = useState(0);
  const [selectedDevices, setSelectedDevices] = useState<IDevice[]>([]);

  useEffect(() => {
    deviceShare.init();
  }, []);

  const rooms = useMemo(() => {
    if (!homes.curHome?.rooms?.[0]) {
      return [];
    }
    return homes.curHome.rooms
      .map(r => {
        const roomDevices = r.devices.filter(
          d => !deviceShare.receiveList.find(sr => sr.shareDeviceList.find(sd => isSameDevice(sd, d)))
        );
        return { ...r, roomDevices };
      })
      .filter(r => r.roomDevices.length > 0);
  }, [homes.curHome?.rooms, deviceShare.receiveList]);

  useEffect(() => {
    if (!rooms[0]) {
      return;
    }
    // setSelectedRoomId(rooms[0].id);
  }, [rooms]);

  const handleSelect = useEvent((device: IDevice) => {
    const index = selectedDevices.findIndex(d => isSameDevice(d, device));
    index < 0
      ? setSelectedDevices([...selectedDevices, device])
      : setSelectedDevices([...selectedDevices.slice(0, index), ...selectedDevices.slice(index + 1)]);
    return;
  });

  const handleShare = useEvent(async () => {
    if (selectedDevices.length === 0) {
      return;
    }
    deviceShare.setSelectedDevices(selectedDevices);
    const res = await deviceShare.createDeviceShareRecord();
    if (!res.success || !res.data) {
      return;
    }
    Taro.navigateTo({
      url: `/pages/share/modes/index?shareId=${res.data}`,
    });
  });

  const styles = dstyles.useDynamicStyle();

  if (!homes.curHome) {
    return null;
  }

  console.log('selectedRoomId', selectedRoomId, toJS(rooms));
  return (
    <PageContainer title='设备分享管理'>
      <View style={styles.container}>
        <ScrollView style={styles.rooms} scrollY>
          <Collapse accordion value={selectedRoomId} onChange={setSelectedRoomId}>
            {rooms.map((r, i) => (
              <Collapse.Item
                key={r.id}
                value={r.id}
                title={r.default ? I18n.t('DEFAULT_GROUP') : I18n.t('GROUP_NO', { no: i })}
                style={styles.item}
              >
                {r.roomDevices.map(d => {
                  const data = devices.data.find(item => isSameDevice(d, item));
                  if (!data) {
                    return null;
                  }
                  const selected = !!selectedDevices.find(item => isSameDevice(d, item));
                  const shareRoom = deviceShare.list.find(sr => sr.roomId === r.id);
                  const shareDevice = shareRoom?.shareDeviceList.find(sd => isSameDevice(sd, d));
                  const productConfig = ProductConfig.getItemForPk(data.productKey);
                  return (
                    productConfig &&
                    productConfig.supportDeviceShare && (
                      <Device
                        key={d.deviceId}
                        data={data}
                        numberOfUsers={shareDevice?.shareNumber ?? 0}
                        isSelectMode
                        selected={selected}
                        onPress={handleSelect}
                      />
                    )
                  );
                })}
              </Collapse.Item>
            ))}
          </Collapse>
        </ScrollView>
        <View style={styles.bottom}>
          <Button
            variant='contained'
            color='primary'
            style={styles.button}
            disabled={selectedDevices.length === 0}
            onClick={handleShare}
          >
            分享
          </Button>
        </View>
      </View>
    </PageContainer>
  );
};

export default observer(AddShareDevices);
